package com.example.shiro;

import com.example.pojo.SysResource;
import com.example.pojo.SysUser;
import com.example.service.ISysResourceService;
import com.example.service.ISysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysResourceService resourceService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录认证主体
        SysUser user = (SysUser) principalCollection.getPrimaryPrincipal();
        //根据userId获取对应权限集合
        List<SysResource> resources = resourceService.queryByUserId(user.getId());
        List<String> permissions = resources.stream()
                .map(e -> e.getPermissionStr()).collect(Collectors.toList());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //授权
        info.addStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取登录账号
        String username = (String) token.getPrincipal();
        System.out.println("登录的账号是：" + username);

        //获取登录用户
        List<SysUser> list = userService.lambdaQuery().eq(SysUser::getUsername, username).list();

        if (list.isEmpty()){
            return null;
        }else {
            SysUser user = list.get(0);
            System.out.println("登录的账号：" + user);
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                    user,
                    user.getPassword(),
                    ByteSource.Util.bytes(user.getUsername()),
                    "MyRealm");

            return info;
        }
    }
}
